package es.uned.etsii.si3.taller.servlets;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import es.uned.etsii.si3.taller.Empleado;
import es.uned.etsii.si3.taller.Usuario;


public class AuthorizationInterceptor extends AbstractInterceptor implements StrutsStatics {
	private static final long serialVersionUID = 1L;
	
	private final Map<String, String> correspondenciaRoles;
	
	public AuthorizationInterceptor() {
		Map<String, String> mapa = new HashMap<String, String>();
		
		mapa.put("administrador", "/administrador");
		mapa.put("jefeseccion", "/jefeseccion");
		mapa.put("jefetaller", "/jefetaller");
		mapa.put("mecanico", "/mecanico");
		mapa.put("cliente", "/cliente");
		
		correspondenciaRoles = mapa;
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		final ActionContext context = invocation.getInvocationContext();
		final ActionProxy proxy = invocation.getProxy();
		String namespace = proxy.getNamespace();
		String action = namespace == "/" ? String.format("/%s", proxy.getActionName())
										 : String.format("%s/%s", namespace, proxy.getActionName());
		
		HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
		HttpSession session = request.getSession();
		
		Object oUsuario = session.getAttribute(Identificador.ATRIBUTO_USUARIO);
		Object oRol     = session.getAttribute(Identificador.ATRIBUTO_ROL);
		Object oRolEf   = session.getAttribute(Identificador.ATRIBUTO_ROL_EF);
		
		if (oRolEf != null) 
			oRol = oRolEf;
		
		if ((oUsuario != null) && (oRol != null)) {
			Usuario usuario = (Usuario)oUsuario;
			String  rol     = (String)oRol;
			
			if (!correspondenciaRoles.get(rol).equals(namespace)) {
				return "ilegal";
			}
		}
		else {
			return "login";
		}
		
		return invocation.invoke();
	}
}